package com.calvin.study.shiro;

import java.util.List;

import javax.security.auth.login.AccountNotFoundException;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.calvin.study.mapper.xml.SysUserMapper;
import com.calvin.study.model.sys.SysUser;
import com.calvin.study.service.sys.ISysUserService;
import com.calvin.study.utils.ApplicationContextUtil;

//自定义Realm完成认证和授权
public class CustomerRealm extends AuthorizingRealm {

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String primaryPrincipal = (String) principals.getPrimaryPrincipal();

		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

		SysUserMapper sysUserMapper = (SysUserMapper) ApplicationContextUtil.getBean("sysUserMapper");
		//查询用户角色
		List<String> roles = sysUserMapper.findRoleByUserName(primaryPrincipal);
		simpleAuthorizationInfo.addRoles(roles);
		/*
		 * roles.forEach(role -> { // 角色 simpleAuthorizationInfo.addRole(role); });
		 */

		if (CollectionUtils.isNotEmpty(roles) && null != roles.get(0)) {
			//查询用户权限
			List<String> permissions = sysUserMapper.findAuthByRoleCodes(roles);
			simpleAuthorizationInfo.addStringPermissions(permissions);
		}
		return simpleAuthorizationInfo;
	}

	// 认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		try {
			// 标识用户身份的唯一凭证 可以是用户名、手机号、证件号…必须是唯一的
			String username = (String) token.getPrincipal();

			ISysUserService sysUserService = (ISysUserService) ApplicationContextUtil.getBean("sysUserService");

			SysUser sysUser = sysUserService.getByUserName(username);
			// 模拟从数据库查询用户名密码信息
			if (null == sysUser) {
				throw new AccountNotFoundException("该用户不存在");
			}
			SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(sysUser.getUserName(),
					sysUser.getPassword(), new ByteSourceUtil(sysUser.getSalt()), this.getName());//ByteSource.Util.bytes(sysUser.getSalt())
			
			return authInfo;
		} catch (Exception e) {
			throw new AuthenticationException("认证失败");
		}
	}

}
